package com.dongliu.controller;

import com.dongliu.domain.Book;
import com.dongliu.domain.User;
import com.dongliu.service.BookService;
import com.dongliu.service.LentRecordService;
import com.dongliu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("book")
public class BookController {

    @Autowired
    private BookService bookService;
    @Autowired
    private LentRecordService lentRecordService;
    @Autowired
    private UserService userService;

    @GetMapping("/id/{id}")
    public Result getById(@PathVariable Integer id) {
        System.out.println("按id查询");
        Book book = bookService.getById(id);
        Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
        String msg = book != null ? "" : "数据查询失败，请重试！";
        return new Result(code, book, msg);
    }

    @GetMapping("/field/{field}")
    public Result getBooks(@PathVariable String field) {
        List<Book> bookList = bookService.getBooks(field);
        Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = bookList != null ? "":"数据查询失败，请重试！";
        return new Result(code, bookList, msg);
    }

    @PostMapping
    public Result createRecord(@RequestBody Book book, HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        // 更新数据
        user = userService.getById(user.getId());
        request.getSession().setAttribute("user", user);
        if(user.getLentNumber() == user.getLimitNumber()){
            return new Result(Code.LEND_ERR, false);
        }
        boolean flag = lentRecordService.createRecord(book, user);
        return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR, flag);
    }

//    @GetMapping("/name/{name}")
//    public Result getByName(@PathVariable String name) {
//        List<Book> bookList = bookService.getByName(name);
//        Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;
//        String msg = bookList != null ? "":"数据查询失败，请重试！";
//        return new Result(code, bookList, msg);
//    }
//
//    @GetMapping("/type/{type}")
//    public Result getByType(@PathVariable String type) {
//        List<Book> bookList = bookService.getByType(type);
//        Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;
//        String msg = bookList != null ? "":"数据查询失败，请重试！";
//        return new Result(code, bookList, msg);
//    }
//
//    @GetMapping("/description/{description}")
//    public Result getByDescription(@PathVariable String description) {
//        List<Book> bookList = bookService.getByDescription(description);
//        Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;
//        String msg = bookList != null ? "":"数据查询失败，请重试！";
//        return new Result(code, bookList, msg);
//    }
}
